package com.cusc.lib_api.http;

import android.widget.Toast;

import com.cusc.lib_api.RetrofitManager;
import com.cusc.lib_api.bean.RespDTO;
import com.cusc.lib_api.bean.RespDTOByLogin;
import com.cusc.lib_api.bean.RespList;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Description: <Rx适配器><br>
 * Author:      mxdl<br>
 * Date:        2019/3/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class RxAdapter {



    /**
     * 线程调度器
     */
    public static ObservableTransformer schedulersTransformer() {
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static ObservableTransformer exceptionTransformer() {

        return observable -> observable
                .map(new HandleFuc())  //这里可以取出BaseResponse中的Result
                .onErrorResumeNext(new HttpResponseFunc());
    }

    private static class HttpResponseFunc<T> implements Function<Throwable, Observable<T>> {
        @Override
        public Observable<T> apply(Throwable t) {
            ResponseThrowable exception = ExceptionHandler.handleException(t);
            if(exception.code ==  ExceptionHandler.SYSTEM_ERROR.TIMEOUT_ERROR ){
                Toast.makeText(RetrofitManager.mContext,"网络不给力哦！",Toast.LENGTH_SHORT).show();
            }
            return Observable.error(exception);
        }
    }

    private static class HandleFuc implements Function<Object,Object> {

        @Override
        public Object apply(Object o) throws Exception {
            if(o instanceof RespDTO) {
                RespDTO respDTO = (RespDTO) o;
                if (respDTO.retCode != ExceptionHandler.APP_ERROR.SUCC) {
                    Toast.makeText(RetrofitManager.mContext, respDTO.retMsg, Toast.LENGTH_SHORT).show();
                }
                return o;
            }
            if (o instanceof RespDTOByLogin){
                RespDTOByLogin respDTOByLogin = (RespDTOByLogin) o;
                if (respDTOByLogin.retCode != ExceptionHandler.APP_ERROR.SUCC) {
                    Toast.makeText(RetrofitManager.mContext, respDTOByLogin.retMsg, Toast.LENGTH_SHORT).show();
                }
                return o;
            }
            if (o instanceof RespList){
                RespList respList = (RespList) o;
                if (respList.retCode != ExceptionHandler.APP_ERROR.SUCC) {
                    Toast.makeText(RetrofitManager.mContext, respList.retMsg, Toast.LENGTH_SHORT).show();
                }
                return o;
            }
            return o;
        }
    }

}
